package P060_ArrayForHighPerformance;

import org.junit.Test;

import java.text.Collator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;

/**
 * Desc:&emsp;&ensp;性能考虑，数组是首选
 *
 * @author 李渊&emsp;liyuan7@yusys.com.cn
 * @version 1.0
 * @since V4.3&emsp;2022/3/24
 */
public class ArrayForHighPerformance {
    final static int LENGTH = 10000;

    @Test
    public void Test1() {
        // 生成数据，1-10000
        int[] dataArr = new int[LENGTH];
        List<Integer> dataList = new ArrayList<>(LENGTH);
        for (int i = 0; i < LENGTH; i++) {
            dataArr[i] = i;
            dataList.add(i,i);
        }
        long startTime = System.nanoTime();
        sum(dataArr);
        long time1= System.nanoTime();
        System.out.println(time1-startTime+"ns");

        startTime= System.nanoTime();
        sum(dataList);
        time1= System.nanoTime();
        System.out.println(time1-startTime+"ns");

    }

    /**
     * 基础类型在栈内存操作，快，速度比集合快约10倍
     * @param data
     * @return
     */
    public static int sum(int[] data) {
        int sum = 0;
        for (int j = 0; j < data.length; j++) {
            sum += data[j];
        }
        return sum;
    }

    /**
     * List多了对基本类型的拆装箱，不在整形池的数据都会产生一个新对象，堆内存的操作相对于栈内存更慢
     * @param data
     * @return
     */
    public static int sum(List<Integer> data) {
        int sum = 0;
        for (int j = 0; j < data.size(); j++) {
            sum += data.get(j);
        }
        return sum;
    }

}
